from flask import Blueprint,request,make_response,jsonify

from util.captcha.captcha import captcha
import json, random, time, requests

from util.comd5 import md5
from util.myjwt import myjwt
from util.myredis import r
from models.user import *

user_blue = Blueprint("userblue",__name__)


@user_blue.route("/getImageCode")
def getImageCode():
    # 生成图片验证码 text文字   image图片流
    name, text, image = captcha.generate_captcha()
    # 从页面获取uuid做为redis key
    uuid = request.args.get("uuid")
    # 存入redis
    r.str_setex(uuid, text, 300)
    # 以流的方式生成图片验证码
    res = make_response(image)
    res.headers["Content-Type"] = 'image/jpg'
    return res

@user_blue.route("/login",methods=["POST"])
# 注册登录
def login():
    data = json.loads(request.data)
    mobile = data["mobile"]
    pwd = data["pwd"]
    if not all([mobile,pwd]):
        return jsonify({"code": 400,"msg":"字段不能为空"})
    admin = Admin_User.query.filter_by(mobile=mobile).first()

    if admin:
        if admin.password != pwd:
            return jsonify({"code": 400, "msg": "密码错误"})
        # 获取页面权限
        menulist,myurl = getMenu(admin.role_id)
        print("页面权限>>>",menulist,'接口权限>>>',myurl)
        list = GetResourceurl(admin.role_id)
        data = {"data": {"userid": admin.id, "mobile": admin.mobile,'role_id':admin.role_id, "exp": int(time.time())}}
        key = 'role_id' + str(data['data']['role_id'])
        r.str_add(key,json.dumps(list))
        token = myjwt.jwt_encode(data)
        return jsonify({"code": 200, "msg": "登录成功","token":token,"mobile":admin.mobile,"user_id":admin.id,"data":menulist,"myurl":myurl,'role_id':admin.role_id})
    user = Admin_User(mobile=mobile,password=pwd,role_id=1)
    db.session.add(user)
    db.session.commit()
    return jsonify({"code": 201, "msg": "注册成功"})

# 页面权限
def getMenu(roleid):
    role = db.session.execute("select res.*,pres.name as pname from role_resource as rr left join resource as res on rr.resource_id=res.id  inner join resource as pres on res.pid=pres.id where rr.role_id=%d and res.type=1 and button_id=4"%int(roleid))
    if role:
        reslist = []
        ids = []
        myurl = []
        for i in role:
            myurl.append(i['url'])
            # 判断父类是否存在，不存在添加
            if i["pid"] not in ids:
                ids.append(i['pid'])
                reslist.append(
                    {"id": i["pid"], "name": i['pname'], "son": [{"id": i['id'], "name": i['name'], 'url': i['url']}]})
            else:
                # 存在，查找父类，遍历父类用子类的pid对比
                for (index, p) in enumerate(reslist):
                    if i['pid'] == p['id']:
                        # 将子类加到父类下
                        reslist[index]['son'].append({"id": i['id'], "name": i['name'], 'url': i['url']})
        return reslist, myurl


def GetResourceurl(role_id):
    sql = db.session.execute("""select res.url from role_resource as rr left join resource as res on rr.resource_id=res.id where rr.role_id=%d and type=2"""%int(role_id))
    list = []
    for i in sql:
        list.append(i.url)
    return list



@user_blue.route('/get_server_audit')
def get_server_audit():
    role_id = request.args.get('role_id')
    q1 = db.session.query(Server).filter(Server.status == 0, Server.role_id == int(role_id))
    q2 = db.session.query(Server1).filter(Server1.status == 0, Server1.role_id == int(role_id))
    q3 = db.session.query(Server2).filter(Server2.status == 0, Server2.role_id == int(role_id))
    ret = q1.union(q2).union(q3).all()
    lst = []
    for i in ret:
        lst.append({
            'id': str(i.code),
            'title': i.title,
            'user_id': i.user_id,
            'type': i.type,
            'desc': i.desc,
            'label': i.label,
            'budget': float(i.budget),
            'mobile': i.mobile,
            'status': i.status,
            'create_time': str(i.create_time)
        })
    return jsonify({
        'code':200,
        'msg':"OK",
        'data':lst
    })


@user_blue.route('/audit_server')
def audit_server():
    code = request.args.get('code')
    title = "Server"
    number = hash(int(code))%3
    if number != 0:
        title = title + str(number)
    title = globals().get(f'{title}')
    server = title.query.filter_by(code=code).first()
    use = Users.query.filter_by(id=server.user_id).first()
    try:
        if use:
            use.money = float(use.money) - float(server.budget)
            use.lock_moeny = float(use.lock_moeny) + float(server.budget)
            db.session.add(use)
        else:
            return jsonify({
                'code':400,
                'msg':"请重新登录"
            })
        if server:
            server.status = 1
            db.session.add(server)
        else:
            return jsonify({
                'code': 400,
                'msg': "数据不存在"
            })
        db.session.commit()
        return jsonify({
            'code': 200,
            'msg': "审核成功"
        })
    except Exception as e:
        print(e)
        return jsonify({
            'code':400,
            'msg':"后端错误"
        })

# 获取全部按钮
@user_blue.route("/getbutton")
def getbutton():
    print("666")
    but = Buttons.query.all()
    if but:
        lst = []
        for i in but:
            if i.id != 4:
                lst.append({
                    "key":i.id,
                    "label":i.name
                })
        return jsonify({"code": 200,"data":lst})

# 获取全部资源
@user_blue.route("/getres")
def getres():
    but = Resource.query.filter(Resource.pid!=0).all()
    print(but)
    if but:
        lst = []
        for i in but:
            lst.append({
                "id": i.id,
                "name": i.name,
                "url":i.url
            })
        return jsonify({"code": 200, "data": lst})

# 配置按钮权限
@user_blue.route("/button_put",methods=["POST"])
def but():
    data = json.loads(request.data)
    roleid = int(data["role_id"])
    resourceid = int(data["resource_id"])
    checkList = data["checkList"]
    # 先删除以前配置的按钮权限
    Roles_Resource.query.filter(Roles_Resource.role_id==roleid,Roles_Resource.resource_id==resourceid,Roles_Resource.button_id!=4).delete()
    db.session.commit()
    for i in checkList:
        # 添加按钮权限
        role = Roles_Resource(role_id=roleid,resource_id=resourceid,button_id=int(i))
        db.session.add(role)
        db.session.commit()
    return jsonify({"code": 200, "msg": "按钮配置成功"})

# 获取页面按钮权限
@user_blue.route("/getbut",methods=["POST"])
def getbut():
    data = json.loads(request.data)
    roleid = int(data["roleid"])
    url = data["url"]
    res = Resource.query.filter_by(url=url).first()
    if res:
        roles = Roles_Resource.query.filter(Roles_Resource.roleid==roleid,Roles_Resource.resourceid==res.id,Roles_Resource.buttonidd !=4).all()
        lst = []
        for i in list(roles):
            lst.append(i.buttonidd)
        return jsonify({"code":200,"data":lst})

# 给角色配置
@user_blue.route('/get_role')
def get_role():
    roles = Role.query.all()
    lst = []
    for i in roles:
        lst.append({
            'id':i.id,
            'name':i.name
        })
    return jsonify({
        'code':200,
        'msg':"OK",
        'data':lst
    })

@user_blue.route('/resource_handler')
def resource_handler():
    role_id = request.args.get('role_id')
    role = Resource.query.filter(Resource.pid>0).all()
    data = [{'key':i.id,'label':i.name} for i in role]
    print('data>>>>>>>>>',data)
    resource_id = Roles_Resource.query.filter_by(role_id=role_id).all()
    lists = []
    for i in resource_id:
        lists.append(i.resource_id)
    print('>>>>>>>>>',lists)
    return jsonify({
        'code':200,
        'msg':"OK",
        'data':data,
        'value':lists
    })


@user_blue.route('/delete_resource',methods=['POST'])
def delete_resource():
    data = json.loads(request.data)
    role_id = int(data['role_id'])
    resource_id = data['resource_id']
    Roles_Resource.query.filter_by(role_id=role_id).delete()
    db.session.commit()
    for i in resource_id:
        add_resrole = Roles_Resource(role_id=role_id,resource_id=int(i),button_id=4)
        db.session.add(add_resrole)
        db.session.commit()
    return jsonify({
        'code':200,
        'msg':"添加资源成功"
    })

@user_blue.route('/add_roles',methods=['POST'])
def add_role():
    role_name = request.args.get('role_name')
    roles = Role.query.filter_by(name=role_name).first()
    if not  roles:
        role = Role(name=role_name)
        db.session.add(role)
        db.session.commit()
        return jsonify({
            'code':200,
            'msg':"添加角色成功"
        })
    else:
        return jsonify({
            'code': 400,
            'msg':"角色已存在"
        })

@user_blue.route('/add_user_role',methods=['POST'])
def add_user_role():
    data = json.loads(request.data)
    user_id = data['user_id']
    role_id = data['role_id']
    if not all([user_id,role_id]):
        return jsonify({
            'code':400,
            'msg':"参数错误"
        })
    use = Admin_User.query.filter_by(id=user_id,role_id=role_id).first()
    if use:
        return jsonify({
            'code':400,
            'msg':"该用户的角色已经是选定角色"
        })
    else:
        role = Admin_User.query.filter_by(id=user_id).update({'role_id':int(role_id)})
        db.session.commit()
        return jsonify({
            'code':200,
            'msg':"配置角色成功"
        })
# select re.*,pre.name as pname from role_resource as rr left join resource as re on rr.resource_id=re.id left join resource as pre on pre.id = re.pid where rr.role_id=2 and re.type=1